package com.example.togethermove.utils;

import android.content.Context;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName: TextColorUtil
 * @Author: csl
 * @Date:
 * @Description: 字符串部分变色 关键字变色
 */
public class TextColorUtil {
    /**
     *
     * @param text title内容
     * @param color 颜色
     * @param keyword 关键字
     * @return
     */
    public static SpannableString matcherSearchTitle(int color, String text, String keyword) {
        String string = text.toLowerCase();
        String key = keyword.toLowerCase();
        Pattern pattern = Pattern.compile(key);
        Matcher matcher = pattern.matcher(string);
        SpannableString ss = new SpannableString(text);
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            ss.setSpan(new ForegroundColorSpan(color), start, end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return ss;
    }

    /**
     * 设置字符串中的数字显示红色
     * @param str
     */
    public static void setNumberTextColor(String str, TextView textView, Context c, int resourcesID){
        char[] s = str.toCharArray();
        SpannableString ss = new SpannableString(str);
        for (int i = 0; i < s.length; i++){
            if (isNum(String.valueOf(s[i]))){
                ss.setSpan(new ForegroundColorSpan(c.getResources().getColor(resourcesID)), i, i+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        textView.setText(ss);
    }

    /**
     * 判断是否是数字
     * @param str
     * @return
     */
    private static boolean isNum(String str) {
        try {

            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
